package org.ligson.org.util;

import com.netflix.loadbalancer.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MyWeightedResponseTimeRule2 extends WeightedResponseTimeRule {
    static AtomicInteger count1 = new AtomicInteger(0);
    static AtomicInteger count2 = new AtomicInteger(0);
    static AtomicInteger count3 = new AtomicInteger(0);


    @Override
    public Server choose(Object key) {
        Server server = super.choose(key);
        log.info("负载均衡结果:{}", server != null ? server.getHostPort() : null);
        AbstractLoadBalancer lb = (AbstractLoadBalancer) getLoadBalancer();
        LoadBalancerStats stats = lb.getLoadBalancerStats();
        if (server != null) {
            ServerStats sss = stats.getSingleServerStat(server);
            log.info("server stat:{}", sss);
            if ("10.6.239.123:8891".equalsIgnoreCase(server.getHostPort())) {
                count1.incrementAndGet();
            } else if ("10.6.239.123:8892".equalsIgnoreCase(server.getHostPort())) {
                count2.incrementAndGet();
            } else if ("10.6.239.123:8893".equalsIgnoreCase(server.getHostPort())) {
                count3.incrementAndGet();
            }
            int sum = (count1.get() + count2.get() + count3.get());
            double count1rate = count1.get() * 1.00 / sum;
            double count2rate = count2.get() * 1.00 / sum;
            double count3rate = count3.get() * 1.00 / sum;
            log.info("\n sum:{} \nserver1 rate:{}%    {}\nserver2 rate:{}%    {}\nserver3 rate:{}%      {}\n", sum, count1rate * 100, count1.get(), count2rate * 100, count2.get(), count3rate * 100, count3.get());

        }

        return server;
    }
}
